<?php
//特殊说明 以sendOrder为例子 generateBusinessSign中的随机数 与 $requestJson 中的随机数相同
class birdApi {
//public $API_URL = 'http://open-anubis.beta.elenet.me/anubis-webapi';
  public $API_URL = 'https://exam-anubis.ele.me/anubis-webapi';//调试域名
  public $APP_ID = '08b60915-a201-465d-ad3d-575b8ec89d54';
  public $SECRET_KEY = '68b7329a-40cd-49c8-b64a-154b10106cc0';
  
  function __CONSTRUCT(){
  	date_default_timezone_set('PRC');
  }
  //获取token使用
  public  function generateSign($appId, $salt, $secretKey) {
    $seed = 'app_id=' . $appId . '&salt=' . $salt . '&secret_key=' . $secretKey;
    return md5(urlencode($seed));
  }
	//商户发出请求使用
  public  function generateBusinessSign($appId, $token, $urlencodeData, $salt) {
    $seed = 'app_id=' . $appId . '&access_token=' . $token
          . '&data=' . $urlencodeData . '&salt=' . $salt;
    return md5($seed);
  }

   /**
     * 发送GET请求
     * @param string $url
     * @param array $param
     * @return bool|mixed
     */
    public  function doGet($url, $param = null)
    {
        if (empty($url) or (!empty($param) and !is_array($param))) {
            throw new InvalidArgumentException('Params is not of the expected type');
        }
        if (!empty($param)) {
            $url = trim($url, '?') . '?' . http_build_query($param);
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_AUTOREFERER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);     //  不进行ssl 认证
        // curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        $result = curl_exec($ch);
        $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        if (!empty($result) and $code == 200) {
            return $result;
        }
        return false;
    }

    /**
     * POST请求
     * @param $url
     * @param $param
     * @return boolean|mixed
     */
    public function doPost($url, $param, $method = "POST")
    {
        // echo 'Request url is ' . $url . PHP_EOL;
        if (empty($url) or empty($param)) {
            throw new InvalidArgumentException('Params is not of the expected type');
        }

        // 验证url合法性
//        if (!filter_var($url, FILTER_VALIDATE_URL)) {
//            throw new InvalidArgumentException('Url is not valid');
//        }

        if (!empty($param) and is_array($param)) {
            $param = urldecode(json_encode($param));
        } else {
            // $param = urldecode(strval($param));
            $param = strval($param);
        }
//				echo $param;die;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        // curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);     //  不进行ssl 认证

        if (strcmp($method, "POST") == 0) {  // POST 操作
          curl_setopt($ch, CURLOPT_POST, true);
        } else if (strcmp($method, "DELETE") == 0) { // DELETE操作
          curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
        } else {
          throw new InvalidArgumentException('Please input correct http method, such as POST or DELETE');
        }

        curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: Application/json'));
        $result = curl_exec($ch);
        $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        if (!empty($result) and $code == '200') {
            return $result;
        }
        return false;
    }

  //添加订单
	/**
	 * 参数示例
	 * $dataArray = array(
		  'transport_info' => array(
		    'transport_name' => '001-测试',
		    'transport_address' => '北京市亦庄开发区西环南路26号嘉捷科技园1号楼307',
		    'transport_longitude' => 121.5156496362,
		    'transport_latitude' => 31.2331643501,
		    'position_source' => 1,
		    'transport_tel' => '13900000000',
		    'transport_remark' => '备注'
		  ),
		  'receiver_info' => array(
		    'receiver_name' => '001-测试',
		    'receiver_primary_phone' => '18603766973',
		    'receiver_second_phone' => '18603766973',
		    'receiver_address' => '北京市亦庄开发区西环南路26号嘉捷科技园1号楼307',
		    'receiver_longitude' => 116.545536,
		    'position_source' => 3,
		    'receiver_latitude' => 39.769718
		  ),
		  'items_json' => array(
		    array(
		      'item_name' => '苹果',
		      'item_quantity'=> 5,
		      'item_price' => 9.50,
		      'item_actual_price' => 10.00,
		      'is_need_package' => 1,
		      'is_agent_purchase' => 1,
		      'agent_purchase_price'=>166
		    ),
		  ),
		  'partner_remark' => '天下萨拉',
		  'partner_order_code' => time(),     // 第三方订单号, 需唯一
		  'notify_url' => 'https://wxdiy.sjwke.com/web/birdtest.php',     //第三方回调 url地址
		  'order_type' => 2,
		  'order_total_amount' => 50.00,
		  'order_actual_amount' => 48.00,
		  'order_weight'=> 12.0,
		  'is_invoiced' => 1,
		  'invoice' => '饿了么',
		  'agent_purchase_price'=>166,
		  'order_payment_status' => 1,
		  'order_payment_method' => 1,
		  'require_payment_pay' => 50.00,
		  'goods_count' => 4,
		  'is_agent_payment' => 1,
		  'require_receive_time' => strtotime('+1 day') * 1000  //注意这是毫秒数
		);
	 * 
	 */	
	 
  public function sendOrder($dataArray) {
    $salt = $this->getRand();
    $dataJson =  json_encode($dataArray, JSON_UNESCAPED_UNICODE);

    // $urlencodeData = urlencode($dataJson);
    $urlencodeData = urlencode($dataJson);
    $sig = $this->generateBusinessSign($this->APP_ID, $this->getToken(), $urlencodeData, $salt);   //生成签名
    $requestJson = json_encode(array(
      'app_id' => $this->APP_ID,
      'salt' => $salt,
      'data' => $urlencodeData,
      'signature' => $sig
    ));
    $url = $this->API_URL . '/v2/order';
    return $this->doPost($url, $requestJson);
  }

    //取消订单
    //目前商户只能在蜂鸟配送允许的状态下进行取消，建议商户先查询订单状态，获得允许取消的状态时再调用取消接口。
    public function cancelOrder($data){
        $appId = $this->APP_ID;
        $url = $this->API_URL . "/v2/order/cancel";
        $token = $this->getToken();
        $dataJson = json_encode($data);
        $salt = $this->getRand();
        $urlencodeData = urlencode($dataJson);
        $sig = $this->generateBusinessSign($appId, $token, $urlencodeData, $salt);   //生成签名

        $requestJson = json_encode(array(
          'app_id' => $appId,
          'salt' => $salt,
          'data' => $urlencodeData,
          'signature' => $sig
        ));
       return $this->doPost($url, $requestJson);
    }
	
		//订单投诉
		/**
		 * $partner_order_code => 订单号
		 * $order_complaint_code = >投诉状态码
		 * $order_complaint_desc => 投诉描述[$order_complaint_code=230 的时候是必须填写]
		 * 状态码列表
		 * 订单投诉编码（230:其他, 150:未保持餐品完整, 160:服务态度恶劣, 190:额外索取费用, 170:诱导收货人或商户退单, 140:提前点击送达, 210:虚假标记异常, 220:少餐错餐, 200:虚假配送, 130:未进行配送）
		 * 
		 */
		function complaint($partner_order_code,$order_complaint_desc='',$order_complaint_code=230){
			if($order_complaint_code==230 && empty($order_complaint_desc)) throw new Exception("请填写投诉描述,或者选择其它的正确状态码", 1);
			
			$appId = $this->APP_ID;
			$url = $this->API_URL . "/v2/order/complaint";
			$token = $this->getToken();		
			$data = array(
				"partner_order_code" => $partner_order_code,
				"order_complaint_code" => $order_complaint_code,
				"order_complaint_time" => $this->msectime(), //订单投诉时间（毫秒）
				"order_complaint_desc" => $order_complaint_desc	//投诉描述
			);
			$dataJson = json_encode($data, JSON_UNESCAPED_UNICODE);			
			$salt = $this->getRand();
			$urlencodeData = urlencode($dataJson);
			$sig = $this->generateBusinessSign($appId, $token, $urlencodeData, $salt);   //生成签名
			
			$requestJson = json_encode(array(
			  'app_id' => $appId,
			  'salt' => $salt,
			  'data' => $urlencodeData,
			  'signature' => $sig
			));
			return $this->doPost($url, $requestJson);   //发送请求
		}
		//查询订单
		/**
		 * $partner_order_code 需要查询的订单号
		 */
		function queryOrder($partner_order_code){
			$appId = $this->APP_ID;
			$url = $this->API_URL . "/v2/order/query";
			$salt = $this->getRand();
			$token = $this->getToken();
			$data = array("partner_order_code" => $partner_order_code);
			$dataJson = json_encode($data, JSON_UNESCAPED_UNICODE);
			$urlencodeData = urlencode($dataJson);
			$sig = $this->generateBusinessSign($appId, $token, $urlencodeData, $salt);
			$requestJson = json_encode(array(
			  'app_id' => $this->APP_ID,
			  'salt' => $salt,
			  'data' => $urlencodeData,
			  'signature' => $sig
			));
//			var_dump($requestJson);die;
			$json = $this->doPost($url, $requestJson);   //发送请求
			$arr = json_decode($json,true)['data'];
			return $arr;
		}
		
		//获取骑手位置和姓名
		/**
		 * 订单号
		 */
		function getRiderLocation($order){
				$url = $this->API_URL . "/v2/order/carrier";
				$salt = $this->getRand();
				$token = $this->getToken();
				$data = array("partner_order_code" => $order);
				$dataJson = json_encode($data, JSON_UNESCAPED_UNICODE);
				$urlencodeData = urlencode($dataJson);
				$sig = $this->generateBusinessSign($this->APP_ID, $token, $urlencodeData, $salt);
				$requestJson = json_encode(array(
				  'app_id' => $this->APP_ID,
				  'salt' => $salt,
				  'data' => $urlencodeData,
				  'signature' => $sig
				));
				$json = $this->doPost($url, $requestJson);   //发送请求
				$arr = json_decode($json,true)['data'];
				return $arr;
		}

		/*********************************************门店接口start*******************************************************/
		//添加门店信息
		/**
		 * return bool 
		 */
		public function addShopInfo($data){
				$url = $this->API_URL . "/v2/chain_store";
				$salt = $this->getRand();
				$token = $this->getToken();
				$dataJson = json_encode($data, JSON_UNESCAPED_UNICODE);
				$urlencodeData = urlencode($dataJson);
				$sig = $this->generateBusinessSign($this->APP_ID, $token, $urlencodeData, $salt);
				$requestJson = json_encode(array(
				  'app_id' => $this->APP_ID,
				  'salt' => $salt,
				  'data' => $urlencodeData,
				  'signature' => $sig
				));
				$json = $this->doPost($url, $requestJson);   //发送请求
				$arr = json_decode($json,true);
				if($arr['code']==200 && $arr['success']){
					return true;
				}else{
					return false;	
				}
		}
		
		//查询门店信息
		/**
		 * chain_store_code => 门店编号 array or string
		 * 单个查询输入字符串
		 * 多个查询需要传入数组
		 */
		public function showShopInfo($chain_store_code){
				$storeArr = [];
				if(gettype($chain_store_code) == "string"){
					$storeArr[] = $chain_store_code;
				}else{
					$storeArr = $chain_store_code;
				}
				$url = $this->API_URL . "/v2/chain_store/query";
				$salt = $this->getRand();
				$token = $this->getToken();
				$data = array("chain_store_code" => $storeArr);
				$dataJson = json_encode($data, JSON_UNESCAPED_UNICODE);
				$urlencodeData = urlencode($dataJson);
				$sig = $this->generateBusinessSign($this->APP_ID, $token, $urlencodeData, $salt);
				$requestJson = json_encode(array(
				  'app_id' => $this->APP_ID,
				  'salt' => $salt,
				  'data' => $urlencodeData,
				  'signature' => $sig
				));
				$json = $this->doPost($url, $requestJson);   //发送请求
				$arr = json_decode($json,true)['data'];
				return $arr;
		}
		
		/**
		 * 更新门店信息
		 * param data : array
		 */
		 public function upShopInfo($data){
		 		$url = $this->API_URL . "/v2/chain_store/update";
				$salt = $this->getRand();
				$token = $this->getToken();
				$dataJson = json_encode($data, JSON_UNESCAPED_UNICODE);
				$urlencodeData = urlencode($dataJson);
				$sig = $this->generateBusinessSign($this->APP_ID, $token, $urlencodeData, $salt);
				$requestJson = json_encode(array(
				  'app_id' => $this->APP_ID,
				  'salt' => $salt,
				  'data' => $urlencodeData,
				  'signature' => $sig
				));
				$json = $this->doPost($url, $requestJson);   //发送请求
				$arr = json_decode($json,true)['data'];
				return $json;
		 }
		 
		 /**
		  * 查询配送服务
		  * 商户通过此接口可以查询门店配送服务能力，包括门店与收货点距离（蜂鸟开放平台默认采用高德步行导航距离计算是否超距，
		  * 若商户使用了其他坐标系，
		  * 系统将进行坐标系转化，转化存在一定的距离误差，以蜂鸟开放平台计算结果为准），收货点是否超出门店配送范围等
		  */
		  public function checkServer($data){
			  	$url = $this->API_URL . "/v2/chain_store/update";
					$salt = $this->getRand();
					$token = $this->getToken();
					$dataJson = json_encode($data, JSON_UNESCAPED_UNICODE);
					$urlencodeData = urlencode($dataJson);
					$sig = $this->generateBusinessSign($this->APP_ID, $token, $urlencodeData, $salt);
					$requestJson = json_encode(array(
					  'app_id' => $this->APP_ID,
					  'salt' => $salt,
					  'data' => $urlencodeData,
					  'signature' => $sig
					));
					$json = $this->doPost($url, $requestJson);   //发送请求
					$arr = json_decode($json,true)['data'];
					return $json;
		  }
		/*********************************************门店接口end*******************************************************/
		
		/**
		 * 回调的信息是个json
		 * 接受方式是file_get_contents('php://input');
		 * $data展示
		 * array(10) {
			  ["carrier_driver_name"]=>
			  string(17) "杨超(调度员)"
			  ["carrier_driver_phone"]=>
			  string(11) "17600270990"
			  ["error_code"]=>
			  string(0) ""
			  ["open_order_code"]=>
			  string(13) "1523505308872"
			  ["order_status"]=>
			  int(1)
			  ["partner_order_code"]=>
			  string(10) "1523505293"
			  ["platform_code"]=>
			  string(0) ""
			  ["push_time"]=>
			  float(1523505428879)
			  ["station_name"]=>
			  string(10) "001-测试"
			  ["station_tel"]=>
			  string(11) "13900000000"
			}
		 */
		function parseCallBackJson($json){
			$res = json_decode($json,true);
			//签名 todo校验签名
			$signature = $res['signature'];
			//返回的详细信息
			$data = urldecode($res['data']);
			$data = json_decode($data,true);
			return $data;
		} 
		
		// 获取当前毫秒时间戳
		function msectime() {
		   list($msec, $sec) = explode(' ', microtime());
		   return (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
		}
    //获取随机数
    function getRand(){
        return mt_rand(1000, 9999);
    }

    function getToken() {
        $salt = $this->getRand();
        // 获取签名
        $sig = $this->generateSign($this->APP_ID, $salt, $this->SECRET_KEY);
        $url = $this->API_URL . '/get_access_token';
        $tokenStr = $this->doGet($url, array('app_id' => $this->APP_ID, 'salt' => $salt, 'signature' => $sig));
        // 获取token
        return json_decode($tokenStr, true)['data']['access_token'];
  }
}

$api = new birdApi();
//生成订单 示例start

//$dataArray = array(
//'transport_info' => array(
//  'transport_name' => '001-测试',
//  'transport_address' => '北京市亦庄开发区西环南路26号嘉捷科技园1号楼307',
//  'transport_longitude' => 121.5156496362,
//  'transport_latitude' => 31.2331643501,
//  'position_source' => 1,
//  'transport_tel' => '13900000000',
//  'transport_remark' => '备注'
//),
//'receiver_info' => array(
//  'receiver_name' => '001-测试',
//  'receiver_primary_phone' => '18603766973',
//  'receiver_second_phone' => '18603766973',
//  'receiver_address' => '北京市亦庄开发区西环南路26号嘉捷科技园1号楼307',
//  'receiver_longitude' => 116.545536,
//  'position_source' => 3,
//  'receiver_latitude' => 39.769718
//),
//'items_json' => array(
//  array(
//    'item_name' => '苹果',
//    'item_quantity'=> 5,
//    'item_price' => 9.50,
//    'item_actual_price' => 10.00,
//    'is_need_package' => 1,
//    'is_agent_purchase' => 1,
//    'agent_purchase_price'=>166
//  ),
//),
//'partner_remark' => '天下萨拉',
//'partner_order_code' => time(),     // 第三方订单号, 需唯一
////'partner_order_code' => 'hello123',     // 第三方订单号, 需唯一
//'notify_url' => 'https://wxdiy.sjwke.com/web/birdtest.php',     //第三方回调 url地址
//'order_type' => 2,
//'order_total_amount' => 50.00,
//'order_actual_amount' => 48.00,
//'order_weight'=> 12.0,
//'is_invoiced' => 1,
//'invoice' => '饿了么',
//'agent_purchase_price'=>166,
//'order_payment_status' => 1,
//'order_payment_method' => 1,
//'require_payment_pay' => 50.00,
//'goods_count' => 4,
//'is_agent_payment' => 1,
//'require_receive_time' => strtotime('+1 day') * 1000  //注意这是毫秒数
//);
//$res = $api->sendOrder($dataArray);
//生成订单 示例end

//解析回调json start
//$json = '{"app_id":"08b60915-a201-465d-ad3d-575b8ec89d54","data":"%7B%22carrier_driver_name%22%3A%22%E6%9D%A8%E8%B6%85%28%E8%B0%83%E5%BA%A6%E5%91%98%29%22%2C%22carrier_driver_phone%22%3A%2217600270990%22%2C%22error_code%22%3A%22%22%2C%22open_order_code%22%3A%221523505308872%22%2C%22order_status%22%3A1%2C%22partner_order_code%22%3A%221523505293%22%2C%22platform_code%22%3A%22%22%2C%22push_time%22%3A1523505428879%2C%22station_name%22%3A%22001-%E6%B5%8B%E8%AF%95%22%2C%22station_tel%22%3A%2213900000000%22%7D","salt":9856,"signature":"78c73e579065dcd65a0e2c0737c2baff"}';
//$res = $api->parseCallBackJson($json);
//解析回调json end

//查询订单start

//查询订单end
//$res = $api->queryOrder('1523518178');
//取消订单start
//$data = array(
//	           "partner_order_code" => '1523518178',
//	           "order_cancel_reason_code" => 2,  //订单取消原因 (2:商家取消)
//	           "order_cancel_code"=> 0,//订单取消编码（0:其他, 1:联系不上商户, 2:商品已经售完, 3:用户申请取消, 4:运力告知不配送 让取消订单, 5:订单长时间未分配, 6:接单后骑手未取件）
//	           "order_cancel_description" => "货品不新鲜",
//	           "order_cancel_time" => time() * 1000
//	       );
//$res = $api->cancelOrder($data);			   
//取消订单end

//投诉接口start
//$res = $api->complaint('hello123');
//投诉接口end

//获取骑手位子start 
//$res = $api->getRiderLocation('1523518178');
//获取骑手位子end


//添加门店start
//$data = [
//		"chain_store_code"=> "A002",
//  "chain_store_name"=> "门店2",
//  "contact_phone"=> "13611581190",
//  "address"=> "上海市",
//  "position_source"=> 3,
//  "longitude"=> "109.690773",
//  "latitude"=> "19.91243",
//  "service_code"=> "1"
//];
//$res = $api->addShopInfo($data);
//添加门店end

//查询门店信息start
//$res = $api->showShopInfo(['A001','A002']);
//查询门店信息end

//更新门店信息start
//$data = [
//		"chain_store_code"=> "A001",
//  "chain_store_name"=> "门店一改",
//];
//$res = $api->upShopInfo($data);
//更新门店信息end

//查询配送服务start 
/**
 * 接口限制：每小时不得超过1次,每天不得超过8次
 */
//$data = [
//		"chain_store_code"=> "A001",//门店编号
//  "position_source"=> 3,
//  "receiver_longitude"=> "109.690773",
//  "receiver_latitude"=> "19.91243"
//];
//$res = $api->checkServer($data);
//查询配送服务end
//echo '<pre>';
//var_dump($res);